package com.black.cat.jvm.rtda.heap.methodarea;


import com.black.cat.jvm.rtda.JObject;
import com.black.cat.jvm.rtda.heap.ClassLoader;

import java.util.HashMap;
import java.util.Map;

public class StringPool {

    private static Map<String, JObject> internedStrs = new HashMap<>();

    public static JObject jString(ClassLoader loader, String goStr) {
        JObject internedStr = internedStrs.get(goStr);
        if (null != internedStr) return internedStr;

        char[] chars = goStr.toCharArray();
        JObject jChars = new JObject(loader.loadClass("[C"), chars);
        
        JObject jStr = loader.loadClass("java/lang/String").newObject();
        jStr.setRefVal("value", "[C", jChars);

        internedStrs.put(goStr, jStr);
        return jStr;
    }

    public static String goString(JObject jStr) {
        JObject charArr = jStr.getRefVar("value", "[C");
        return new String(charArr.chars());
    }

}
